/*******************************************************************************
 * Copyright (c) 2011 EclipseDevX.org and others.
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at:
 * 
 *     http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipsedevx.appengine.usage;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

@SuppressWarnings("serial")
public class UsageStatsServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(UsageStatsServlet.class.getName());
	
	public UsageStatsServlet() {
		
	}
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		final String USER_AGENT = "DevX";
		final String HEADER_PREFIX = "DevX-";
		
		// "User-Agent", "DevX"
		if (req.getHeader("User-Agent").startsWith(USER_AGENT)) {
			Map<String, String> headers = new HashMap<String, String>();
			
			for (Object o : Collections.list(req.getHeaderNames())) {
				String key = (String)o;
				
				// "DevX-"
				if (key.startsWith(HEADER_PREFIX)) {
					String value = req.getHeader(key);
					
					key = key.substring(HEADER_PREFIX.length());
					value = URLDecoder.decode(value, "UTF-8");
					
					headers.put(key, value);
				}
			}
			
			storeUsageInfo(headers);
		}
		
		resp.setContentType("text/plain");
		resp.getWriter().println("[-]");
		resp.getWriter().close();
	}

	private void storeUsageInfo(Map<String, String> headers) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		try {
			Entity data = new Entity("UsageData");
			data.setProperty("upload.time", DateUtils.getNowDate());
			
			for (String key : headers.keySet()) {
				data.setProperty(key, headers.get(key));
			}
			
			datastore.put(data);
		} catch (RuntimeException re) {
			log.log(Level.SEVERE, "Error storing usage data", re);
		}
	}
	
}
